# Project: From Home Base to Swing States: The Evolution of Digital Advertising 
#          Strategies during the 2020 US Presidential Primary
# Authors: NaLette Brodnax and Piotr Sapiezynski

library(tidyverse)

ads <- read_csv('replication_data_monthly.csv')

# Fit by month (simple with no random slopes and no interactions)
mod_simple <- function(df, mo){
  data <- filter(df, month == mo)
  fit <- lm(budget_frac_per_resident ~ is_home + swing + feb + march, 
           data = data)
  return(fit)
} 

# Months to fit: Jan 2019 (month 1) thru Feb 2020 (month 14)
months <- seq(1,14,1)
all_fits <- lapply(months, function(x) mod_simple(ads, x))

# Convert results to dataframe
out <- lapply(all_fits, function(x) tidy(x)) %>% 
  bind_rows()

# Create a column for the month indicator for each coefficient
m = NULL
for (i in months){
  m = c(m, rep(i,5))
}

mon = tibble(month = m)

# Export estimate data for plots
out_coef <- out %>%
  bind_cols(mon) %>% 
  filter(term != '(Intercept)')

# Plots
ggplot(aes(month, estimate, group_term), data=out_coef) + geom_line() + 
  geom_point() + geom_errorbar(aes(ymin=estimate-std.error, ymax=estimate+std.error), 
                               width=.1) + facet_wrap(vars(term)) +
  scale_x_continuous(breaks = seq(1,14,3)) 
